package net.apexes.wsonrpc.client.support.websocket;

import java.net.URI;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

class WebSocketHandshake {
    
    private static final String WEBSOCKET_VERSION = "13";

    private final URI url;
    private final String protocol;
    private final String nonce;
    private final Map<String, String> extraHeaders;

    public WebSocketHandshake(URI url, String protocol, Map<String, String> extraHeaders) {
        this.url = url;
        this.protocol = protocol;
        this.extraHeaders = extraHeaders;
        this.nonce = this.createNonce();
    }

    public byte[] getHandshake() {
        String path = url.getPath();
        String query = url.getQuery();
        path += query == null ? "" : "?" + query;
        String host = url.getHost();

        if (url.getPort() != -1) {
            host += ":" + url.getPort();
        }

        LinkedHashMap<String, String> header = new LinkedHashMap<String, String>();
        header.put("Host", host);
        header.put("Upgrade", "websocket");
        header.put("Connection", "Upgrade");
        header.put("Sec-WebSocket-Version", WEBSOCKET_VERSION);
        header.put("Sec-WebSocket-Key", this.nonce);

        if (this.protocol != null) {
            header.put("Sec-WebSocket-Protocol", this.protocol);
        }

        if (this.extraHeaders != null) {
            for (Map.Entry<String, String> entry : this.extraHeaders.entrySet()) {
                String fieldName = entry.getKey();
                // Only checks for Field names with the exact same text,
                // but according to RFC 2616 (HTTP) field names are case-insensitive.
                if (!header.containsKey(fieldName)) {
                    header.put(fieldName, entry.getValue());
                }
            }
        }

        String handshake = "GET " + path + " HTTP/1.1\r\n";
        handshake += this.generateHeader(header);
        handshake += "\r\n";
        return handshake.getBytes();
    }

    private String generateHeader(LinkedHashMap<String, String> headers) {
        StringBuilder header = new StringBuilder();
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            header.append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n");
        }
        return header.toString();
    }

    private String createNonce() {
        byte[] nonce = new byte[16];
        for (int i = 0; i < 16; i++) {
            nonce[i] = (byte) rand(0, 255);
        }
        return Base64.encodeToString(nonce, false);
    }

    public void verifyServerStatusLine(String statusLine) {
        int statusCode = Integer.parseInt(statusLine.substring(9, 12));

        if (statusCode == 407) {
            throw new WebSocketException("connection failed: proxy authentication not supported");
        } else if (statusCode == 404) {
            throw new WebSocketException("connection failed: 404 not found");
        } else if (statusCode != 101) {
            throw new WebSocketException("connection failed: unknown status code " + statusCode);
        }
    }

    public void verifyServerHandshakeHeaders(HashMap<String, String> headers) {
        if (!"websocket".equals(headers.get("upgrade").toLowerCase(Locale.US))) {
            throw new WebSocketException("connection failed: missing header field in server handshake: Upgrade");
        } else if (!"upgrade".equals(headers.get("connection").toLowerCase(Locale.US))) {
            throw new WebSocketException("connection failed: missing header field in server handshake: Connection");
        }
    }

    private int rand(int min, int max) {
        return (int) (Math.random() * max + min);
    }
}
